package com.jthinker.blog.service;

import com.alibaba.fastjson.JSON;
import com.jthinker.blog.bean.enu.Dict;
import com.jthinker.blog.bean.vo.Constant;
import com.jthinker.blog.util.RSAUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * User: Gang Chen
 * Date: 2015/7/20 21:00
 */
@Service
public class InitService implements ServletContextAware
{
    private static final Logger LOGGER = LoggerFactory.getLogger(InitService.class);

    @Override
    public void setServletContext(ServletContext servletContext)
    {
        Reflections reflections = new Reflections("com.jthinker.blog.bean.enu");
        Set<Class<? extends Dict>> classes = reflections.getSubTypesOf(Dict.class);

        Map<String, Map<String, String>> dictMap = new CaseInsensitiveMap();
        LOGGER.info("init start--------------------------");
        for (Class clazz : classes)
        {
            Map<String, String> dict = new HashMap<String, String>();
            dictMap.put(clazz.getSimpleName(), dict);
            Object[] enums = clazz.getEnumConstants();
            for (Object o : enums)
            {
                Dict d = (Dict) o;
                dict.put(d.getKey(), d.getText());
            }
        }

        servletContext.setAttribute(Constant.DICT_MAP, dictMap);
        servletContext.setAttribute(Constant.DICT_MAP_JSON, JSON.toJSONString(dictMap));

        KeyPair keyPair = RSAUtils.getKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        servletContext.setAttribute(Constant.MODULUS, new String(Hex.encodeHex(publicKey.getModulus().toByteArray())));
        servletContext.setAttribute(Constant.EXPONENT, new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray())));
        LOGGER.info("init end-------------------------");
    }
}
